package com.estar.platform.caseInfo.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSTypegroup;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.estar.app.appsrvyyabx.mobile.domain.vo.CarVO;
import com.estar.app.business.common.service.AppService;
import com.estar.app.business.mobileLogin.utils.ObjCopyUtils;
import com.estar.platform.caseInfo.entity.TmblCarInfoEntity;
import com.estar.platform.caseInfo.entity.TmblSurveyInfoEntity;

/*高速公路案件审核*/

@Controller
@RequestMapping("/surveyInfoByHighwayController")
@Scope("prototype")
public class SurveyInfoByHighwayController extends BaseController{
	@Autowired
	AppService appService;
	
	@RequestMapping(params = "toView")
	public ModelAndView toList(HttpServletRequest request) {
		return new ModelAndView("gdia/caseInfo/carInfoByHighwayList");
	}
	
	/*显示需要审核的案件列表*/
	@RequestMapping(params = "carList")
	public void carList(TmblSurveyInfoEntity surveyInfo, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TmblSurveyInfoEntity.class, dataGrid);

		String reportNo = surveyInfo.getReportNo();
		surveyInfo.setReportNo("");
		String carsNo = surveyInfo.getCarsNo();
		surveyInfo.setCarsNo("");
		String workSpace=surveyInfo.getWorkSpace();
		surveyInfo.setWorkSpace("");
		String yiCarNo=surveyInfo.getYiCarNo();
		surveyInfo.setYiCarNo("");
		
		String jia=surveyInfo.getJiaDriName();
		surveyInfo.setJiaDriName("");
		
		String yi =surveyInfo.getYiDriName();
		surveyInfo.setYiDriName("");
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, surveyInfo, request.getParameterMap());
		try {

			/******* 取当前登录登录人所能操作机构代码 ***/
			TSUser user = ResourceUtil.getSessionUserName(); // 取session用户
			List<TSUserOrg> userOrgList = appService.findByProperty(TSUserOrg.class, "tsUser.id", user.getId());
			List<String> orgs = new ArrayList<String>();
			for (int i = 0; i < userOrgList.size(); i++) {
				String orgCode = (String) userOrgList.get(i).getTsDepart().getId();
				orgs = getPersonCode(orgs, orgCode, appService);
			}

			// 自定义追加查询条件
			CriteriaQuery subCq = new CriteriaQuery(TmblCarInfoEntity.class);

			subCq.setProjection(Property.forName("reportNo"));
			subCq.or(Restrictions.in("compulsoryCompany", orgs.toArray()),
					Restrictions.in("businessCompany", orgs.toArray()));// 取保险公司名称
			subCq.add();
			
			cq.or(Property.forName("reportNo").in(subCq.getDetachedCriteria()),
					Restrictions.in("empDptCde", orgs.toArray()));

			//只看高速
			cq.createAlias("appUser", "c");
			cq.eq("c.area", "2");
			//只查5天内
			Map<String, String[]> m=request.getParameterMap();
			String[] begin= m.get("createTm_begin");
			String[] end=m.get("createTm_end");
			if(begin==null || end==null){
				Date date1=new Date();
				Calendar cal = Calendar.getInstance();
				cal.setTime(date1);
				cal.add(Calendar.DATE, -5);//前五天
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				cq.add(Restrictions.ge("createTm", cal.getTime()));
				cq.add(Restrictions.le( "createTm",date1));
			}
			
			cq.or(Restrictions.eq("caseStatus", "S"), Restrictions.eq("caseStatus", "F"));// 案件状态
			if(surveyInfo.getSurveyExamine()!=null && !surveyInfo.getSurveyExamine().equals("")){
				 cq.eq("surveyExamine", surveyInfo.getSurveyExamine());//审核不通过
				}else{
				 cq.eq("surveyExamine", "n");//审核新案件
			}			
			if (null != carsNo && !"".equals(carsNo)) {
				cq.like("carsNo", "%" + carsNo.toUpperCase() + "%");
			}
			if (null != yiCarNo && !"".equals(yiCarNo)) {
				cq.like("yiCarNo", "%" + yiCarNo.toUpperCase() + "%");
			}
			if (null != reportNo && !"".equals(reportNo)) {
				cq.like("reportNo", "%" + reportNo.toUpperCase() + "%");
			}
			if (StringUtil.isNotEmpty(workSpace)) {
				cq.like("workSpace", "%" + workSpace + "%");
			}
			if (StringUtil.isNotEmpty(jia)) {
				cq.like("jiaDriName", "%" + jia + "%");
			}
			if (StringUtil.isNotEmpty(yi)) {
				cq.like("yiDriName", "%" + yi + "%");
			}
			cq.addOrder("checkFlag", SortDirection.asc);
			cq.addOrder("dangerTime", SortDirection.desc);

			cq.add();
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		this.appService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/*显示审核的案件详情*/
	@RequestMapping(params = "carInfo")
	public ModelAndView carInfo(HttpServletRequest request) {

		String reportNo = request.getParameter("reportNo");

		CriteriaQuery cq = new CriteriaQuery(TmblSurveyInfoEntity.class);
		cq.eq("reportNo", reportNo);
		cq.add();
		TmblSurveyInfoEntity surveyInfo = (TmblSurveyInfoEntity) appService.getListByCriteriaQuery(cq, false).get(0);
		if (!"2".equals(surveyInfo.getCheckFlag())) {
			surveyInfo.setCheckFlag("1");
		}

		appService.saveOrUpdate(surveyInfo);
		request.setAttribute("surveyInfo", surveyInfo);

		// 获取事故名字
		TSTypegroup tg = appService.findUniqueByProperty(TSTypegroup.class, "typegroupcode", "accident");
		String accidentName = null;
		for (TSType tc : tg.getTSTypes()) {// 父类中有个获取其所有子类的list方法，遍历这些list
			if (tc.getTypecode().equals(surveyInfo.getAccidentAfter())) {// 判断赋值
				accidentName = tc.getTypename();
			}
		}
		request.setAttribute("accidentName", accidentName);

		// 查出登录用户的角色，属于保险公司不显示电话号码
		TSUser user = ResourceUtil.getSessionUserName();// 通过session获取登录用户
		String departOrgCode = "";
		String check = "F";
		if (user != null) {
			List<TSUserOrg> tSUserOrgs = appService.findByProperty(TSUserOrg.class, "tsUser.id", user.getId());

			if (tSUserOrgs.size() > 0) {
				for (TSUserOrg tSUserOrg : tSUserOrgs) {
					departOrgCode += tSUserOrg.getTsDepart().getOrgCode() + ",";
				}
			}
			// 一用户一组织的情况下，判断开头前4个字符，因为保险公司都是以A06A开头
			if (departOrgCode.length() > 3) {// 长度大于3，因为有些组织代码只有3位，3位的组织不是保险公司
				if (departOrgCode.substring(0, 4).equals("A06A")) {
					check = "T";
				}
			}

		}
		request.setAttribute("check", check);

		String hql = "from TmblCarInfoEntity where t_report_no=?";
		List<TmblCarInfoEntity> carInfoList = appService.findHql(hql, reportNo);

		List<CarVO> carList = new ArrayList<CarVO>();

		for (int i = 0; i < carInfoList.size(); i++) {
			CarVO car = new CarVO();
			car = (CarVO) ObjCopyUtils.beansCopyForUpdate(carInfoList.get(i), car);

			CriteriaQuery cq1 = new CriteriaQuery(TSDepart.class);
			cq1.eq("orgCode", car.getCompulsoryCompany());
			cq1.add();
			List<TSDepart> comDptList = appService.getListByCriteriaQuery(cq1, false);
			car.setCompulsoryCompany(comDptList.get(0).getDepartname());

			CriteriaQuery cq2 = new CriteriaQuery(TSDepart.class);
			cq2.eq("orgCode", car.getBusinessCompany());
			cq2.add();
			List<TSDepart> busDptList = appService.getListByCriteriaQuery(cq2, false);
			car.setBusinessCompany(busDptList.get(0).getDepartname());

			carList.add(car);
		}

		request.setAttribute("carInfoList", carList);
		//案件审核
				String key="yes";
				String mess="";
			    if(surveyInfo.getSurveyExamine().equals("p")){
					mess="该案件已经审核";
					key="no";
				}else{
					if(StringUtil.isNotEmpty(surveyInfo.getSurveyExamineInfo())){
					mess="审核不合格原因："+surveyInfo.getSurveyExamineInfo();
					}
				}
				request.setAttribute("key", key);
				request.setAttribute("mess", mess);

		return new ModelAndView("gdia/caseInfo/carInfoByHighway");
	}
	
	@RequestMapping(params = "doCheckCase")
	@ResponseBody
	public String doCheckCase(HttpServletRequest request, String id,String mess) {
		String message = null;
		try {
			
			TmblSurveyInfoEntity survey=appService.findUniqueByProperty(TmblSurveyInfoEntity.class, "reportNo",id);
			
			if(mess==null || mess.equals("")){
				survey.setSurveyExamine("p");
				message = "审核成功！";
			}else{
				survey.setSurveyExamine("f");
				survey.setSurveyExamineInfo(mess);
				message = "已存储不通过原因！";
			}
			//记录修改人员
			TSUser u = ResourceUtil.getSessionUserName();
			survey.setSurveyExamineUser(u.getRealName());
			appService.updateEntitie(survey);
			
		} catch (Exception e) {
			message = "审核失败！";
			e.printStackTrace();
		}
		String json="{\"msg\":\""+message+"\"}";
		return json;
	}
}
